package com.ybc.chinese.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.ybc.chinese.R;
import com.ybc.chinese.activity.GalleryActivity;
import com.ybc.chinese.bean.Joke;
import com.ybc.chinese.utils.ImageUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>笑话大全<p/>
 * Created by Yubch on 17/2/16.
 */
public class JokeAdapter extends BaseAdapter {
    private Context mCtx;
    private List<Joke.ResultBean> datas;

    public JokeAdapter(Context ctx) {
        mCtx = ctx;
        datas = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int i) {
        return datas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        final Joke.ResultBean resultBean = datas.get(position);
        if(convertView == null) {
            convertView = LayoutInflater.from(mCtx).inflate(R.layout.item_joke, null);
            holder = new Holder();
            holder.ivPic = (ImageView) convertView.findViewById(R.id.iv_pic);
            holder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }
        if(resultBean != null) {
            final String url = resultBean.getUrl();
            if(!TextUtils.isEmpty(url)) {
                if(url.contains(".gif")) {
                    ImageUtil.displayGif(mCtx, holder.ivPic, url, R.mipmap.ic_default);
                } else {
                    ImageUtil.displayPic(mCtx, holder.ivPic, url, R.mipmap.ic_default);
                }
            }
            holder.tvContent.setText(resultBean.getContent());
            holder.ivPic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    List<String> urls = new ArrayList<String>();
                    urls.add(resultBean.getUrl());
                    mCtx.startActivity(GalleryActivity.newIntent(mCtx, urls, 0, true));
                }
            });
        }
        return convertView;
    }

    class Holder {
        ImageView ivPic;
        TextView tvContent;
    }

    public void setData(List<Joke.ResultBean> resultBeen, boolean isMore) {
        if(!isMore && getCount() > 0) {
            datas.clear();
        }
        datas.addAll(resultBeen);
        notifyDataSetChanged();
    }
}
